package com.mantou.mantouaiagent.config.chatmemory;

import com.mantou.mantouaiagent.util.SpringSecutiryUtil;
import com.mantou.mantouaiagent.util.ThreadLocalUtil;
import org.springframework.ai.chat.memory.ChatMemory;
import org.springframework.ai.chat.messages.Message;
import org.springframework.data.redis.core.ListOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Set;

@Component
public class RedisChatMemory implements ChatMemory {

    private final RedisTemplate<String, Message> messageRedisTemplate;

    private static final String REDIS_KEY_PREFIX ="CHAT_MEMORY";

    public RedisChatMemory(RedisTemplate<String, Message> messageRedisTemplate) {
        this.messageRedisTemplate = messageRedisTemplate;

    }

    @Override
    public void add(String conversationId, List<Message> messages) {
        // 将新消息追加到列表尾部
        messageRedisTemplate.opsForList().rightPushAll(getKey(conversationId), messages);
    }

    @Override
    public List<Message> get(String conversationId, int lastN) {
        ListOperations<String, Message> ops = messageRedisTemplate.opsForList();
        String key = getKey(conversationId);
        // 获取最后N条消息（从尾部倒数）
        long size = ops.size(key) != null ? ops.size(key) : 0;
        return ops.range(key, Math.max(0, size - lastN), -1);
    }

    @Override
    public void clear(String conversationId) {
        messageRedisTemplate.delete(conversationId);
    }

    private String getKey(String conversationId) {
        return REDIS_KEY_PREFIX +":"+conversationId;
    }


}